<template>
    <div>
        <el-card header="大棚位置">
            <div id="gdmap" style="width: 100%;height: 500px;"></div>
        </el-card>
    </div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import setting from '../../../settings';
import { getGreenhouse } from "@/api/system/greenhouse";
export default {
    name: "map",
    components: {

    },
    data() {
        return {
            greenhouseId: null,
            map: null,
            location: {
                lng: null,
                lat: null,
            },
            mapOptions: {
                securityJsCode: setting.amap.securityJsCode,
                key: setting.amap.key, // 申请好的Web端开发者Key，首次调用 load 时必填
                plugins: ["AMap.Scale"], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
            },
        }
    },
    created() {
        this.greenhouseId = this.$route.params && this.$route.params.greenhouseId;
    },
    mounted() {
        this.loadLocation()
    },
    unmounted() {
        this.map?.destroy();

    },
    beforeDestroy() {

    },
    methods: {
        async initAMap() {
            window._AMapSecurityConfig = {
                securityJsCode: this.mapOptions.securityJsCode,
            };
            await AMapLoader.load(this.mapOptions);
            this.map = new AMap.Map("gdmap", {
                // 设置地图容器id
                zoom: 15, // 初始化地图级别
            });
        },
        //获取实时定位数据
        async loadLocation() {
            let response = await getGreenhouse(this.greenhouseId);
            let location = response.data;
            this.location.lng = location.lng;
            this.location.lat = location.lat;
            this.initAMap().then(() => {
                if (!this.location.lng || !this.location.lat) {
                    return
                }
                //标注
                this.map.setCenter([this.location.lng, this.location.lat]);
                let marker = new AMap.Marker({
                    icon: "http://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png",
                    position: [this.location.lng, this.location.lat],
                    offset: new AMap.Pixel(-13, -30)
                });
                marker.setMap(this.map);
            });
        },
    }
}
</script>
